<template>
  <div class="flex flex-col h-full">
    <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '70px' } }">
        <a-form-item name="zjm" label="" class="w-[280px] ml-2">
          <a-input v-model:value="formState.zjm" placeholder="姓名/助记码/信息卡号/病历卡号" />
        </a-form-item>
        <a-form-item name="dateRange" label="配镜时间" class="w-[320px] ml-2">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="freeRange" label="缴费时间" class="w-[320px] ml-2">
          <a-range-picker v-model:value="formState.freeRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="paymentStatus" label="" class="w-[350px] ml-2">
          <a-radio-group v-model:value="formState.paymentStatus">
            <a-radio value="-1">全部</a-radio>
            <a-radio value="0">未缴费</a-radio>
            <a-radio value="1">已缴费</a-radio>
            <a-radio value="2">已退费</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="isOutside" label="" class="w-[220px] ml-2">
          <a-radio-group v-model:value="formState.isOutside">
            <a-radio value="">全部</a-radio>
            <a-radio value="1">外购</a-radio>
            <a-radio value="0">非外购</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="xsdh" label="销售单号" class="w-[280px] ml-2">
          <a-input v-model:value="formState.xsdh" placeholder="销售单号" />
        </a-form-item>
        <a-form-item name="phone" label="电话号码" class="w-[280px] ml-2">
          <a-input v-model:value="formState.phone" placeholder="电话号码" />
        </a-form-item>
        <a-form-item name="phone" label="供应商" class="w-[280px] ml-2">
          <SelectTable v-model:value="formState.gysmc" type="视光供应商" @input-change="onInputChange" @select="onSelectSupplier" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-end mb-2">
        <a-button class="mr-2" @click="onPrintCustom">打印定制镜</a-button>
        <BaseExport
          type="视光"
          name="销售单"
          code="000461"
          :search-params="{
            ...formState,
            jytimestdate: formState.freeRange?.[0],
            jytimeeddate: formState.freeRange?.[1],
            paymentStatus: formState.paymentStatus === '-1' ? undefined : formState.paymentStatus
          }"
          >导出</BaseExport
        >
      </div>
      <BaseTable
        fill
        bordered
        column-code="000461"
        :loading="loading"
        :extra-height="50"
        :scroll="{ x: 2400 }"
        :data-source="tableData"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex == 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'id'">
            <PopoverTable :config="detailConfig" :params="{ id: record.id }" :width="1600">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'isOutside'">
                  <div>{{ popRecord.isOutside === '1' ? '是' : '否' }}</div>
                </template>
                <template v-if="popColumn.dataIndex === 'payItemName'">
                  <MedicineInfo :value="{ mc: popRecord.payItemName, gg: popRecord.specification }" />
                </template>
              </template>
              {{ record.id }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex == 'prescription'">
            <!-- 1：远用 2：近用 -->
            <a-tooltip placement="topLeft">
              <template #title
                >{{ record.longOrShortStr }}<br />
                {{ record.zzcfyy }}<br />
                {{ record.zzcfzy }}</template
              >
              <span class="cursor-pointer"
                >{{ record.longOrShortStr }}
                {{ record.zzcfyy }}
                {{ record.zzcfzy }}</span
              >
            </a-tooltip>
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" size="small" class="mr-2" @click="onRemark(record)">备注</a-button>
            <a-button type="link" size="small" class="mr-2" @click="onPrintSale(record)">销售单</a-button>
            <a-button type="link" size="small" @click="onPrintFinal(record)">处方</a-button>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="column in columnsData" :key="column.dataIndex">
                <a-table-summary-cell v-if="column.dataIndex === 'xh'"> 合计 </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'dpJe'">
                  <div class="text-right">￥{{ formatAmount(summaryData.dpJe || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'downPaymentAmount'">
                  <div class="text-right">￥{{ formatAmount(summaryData.downPaymentAmount || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'payAmount'">
                  <div class="text-right">￥{{ formatAmount(summaryData.payAmount || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else>-</a-table-summary-cell>
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </BaseTable>
    </a-card>
    <Edit v-model:open="editOpen" :row-data="rowData" @success="getData" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { formatAmount } from '@/utils/format.js'
import Edit from './Edit'

const formRef = ref(null)
const rowData = ref({})
const editOpen = ref(false)
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  freeRange: [],
  paymentStatus: '-1',
  isOutside: '',
  gysbh: ''
})
const detailConfig = ref({
  url: '/optometry/ooadolescentcheck/GetOoOpticianSubrecordeAllList',
  columnCode: '000266',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})
const { loading, tableData, pagination, getData } = useTable({
  url: '/optometry/ooadolescentcheck/getSalesOrdeRetrievaldList',
  immediate: true,
  formatParams: () => {
    return {
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      jytimestdate: formState.value.freeRange?.[0],
      jytimeeddate: formState.value.freeRange?.[1],
      ...formState.value,
      paymentStatus: formState.value.paymentStatus === '-1' ? undefined : formState.value.paymentStatus
    }
  },
  onSuccess: () => {
    getSummaryData()
  }
})
onMounted(() => {
  getTableColumns()
})

//获取表头
const columnsData = ref([])
const getTableColumns = async () => {
  const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: '000461' })
  if (code !== 0) return message.error(code)
  columnsData.value = data.filter((item) => !item.isHide)
}
const summaryData = ref({})
const getSummaryData = async () => {
  const { code, data } = await post('/optometry/ooadolescentcheck/getSalesOrdeRetrievaldListHJ', {
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    jytimestdate: formState.value.freeRange?.[0],
    jytimeeddate: formState.value.freeRange?.[1],
    ...formState.value,
    paymentStatus: formState.value.paymentStatus === '-1' ? undefined : formState.value.paymentStatus
  })
  if (code !== 0) return message.error(code)
  summaryData.value = data || {}
}
const onPrintSale = async (row) => {
  const { code, msg, data } = await post('/optometry/ooadolescentcheck/getPrintOoOpticianRecord', {
    xsdh: row.id
  })
  if (code !== 0) return message.error(msg || '打印失败')
  window.openExe?.rpt(data) //调用winform打印
}
const onPrintFinal = async (row) => {
  const { code, msg, data } = await post('/optometry/ooadolescentcheck/getPrintTheFinalPrescription', {
    xsdh: row.id
  })
  if (code !== 0) return message.error(msg || '打印失败')
  window.openExe?.rpt(data) //调用winform打印
}
const onSelectSupplier = (event) => {
  formState.value.gysbh = event.id
  formState.value.gysmc = event.supplierName
}
const onRemark = (row) => {
  rowData.value = { ...row }
  editOpen.value = true
}
const onInputChange = (e) => {
  if (!e) {
    formState.value.gysbh = ''
    formState.value.gysmc = ''
  }
}
const onPrintCustom = async () => {
  const { code, msg, data } = await post('/optometry/ooadolescentcheck/getPrintedCustomizedPieces', {
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    jytimestdate: formState.value.freeRange?.[0],
    jytimeeddate: formState.value.freeRange?.[1],
    paymentStatus: formState.value.paymentStatus === '-1' ? undefined : formState.value.paymentStatus,
    phone: formState.value.phone,
    xsdh: formState.value.xsdh,
    zjm: formState.value.zjm,
    isOutside: formState.value.isOutside,
    gysbh: formState.value.gysbh
  })
  if (code !== 0) return message.error(msg || '打印失败')
  window.openExe?.rpt(data) //调用winform打印
}
</script>
